package com.rymcu.forest.util;

import com.rymcu.forest.dto.TokenUser;
import com.rymcu.forest.entity.User;
import com.rymcu.forest.mapper.UserMapper;
import com.rymcu.forest.util.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.core.AuthenticationException;

import java.util.Objects;

/**
 * @author ronger
 * @deprecated 推荐使用 SecurityUtils 获取当前用户信息
 */
@Deprecated
public class UserUtils {

    private static final UserMapper userMapper = SpringContextHolder.getBean(UserMapper.class);
    private static final JwtUtils jwtUtils = SpringContextHolder.getBean(JwtUtils.class);

    /**
     * 通过token获取当前用户的信息
     * @deprecated 请使用 SecurityUtils.getCurrentUserId()
     */
    @Deprecated
    public static User getCurrentUserByToken() {
        try {
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId != null) {
                return userMapper.selectByPrimaryKey(userId);
            }
        } catch (Exception e) {
            throw new AuthenticationException("获取用户信息失败") {};
        }
        throw new AuthenticationException("用户未登录") {};
    }

    /**
     * 通过token获取TokenUser
     * @deprecated 请使用 SecurityUtils.getCurrentTokenUser()
     */
    @Deprecated
    public static TokenUser getTokenUser(String token) {
        if (StringUtils.isNotBlank(token) && jwtUtils.validateToken(token)) {
            Long userId = jwtUtils.getUserIdFromToken(token);
            if (userId != null) {
                User user = userMapper.selectByPrimaryKey(userId);
                if (Objects.nonNull(user)) {
                    TokenUser tokenUser = new TokenUser();
                    BeanCopierUtil.copy(user, tokenUser);
                    tokenUser.setAccount(user.getAccount());
                    tokenUser.setToken(token);
                    return tokenUser;
                }
            }
        }
        throw new AuthenticationException("无效的token") {};
    }

    public static boolean isAdmin(String email) {
        return userMapper.hasAdminPermission(email);
    }
}
